<template>
  <div class="page-container">
    <div class="book-create">
      <h2>创建新书</h2>
      <form @submit.prevent="openDialog">
        <!-- 书名 -->
        <div class="form-group">
          <el-form-item label="书名" required>
            <el-input v-model="form.title" placeholder="请输入书名"></el-input>
          </el-form-item>
        </div>

        <!-- 封面图片上传 -->
        <div class="form-group">
          <el-form-item label="封面图片" required>
            <div class="upload-container" @click="triggerFileInput">
              <input 
                id="coverImageUpload" 
                type="file" 
                accept="image/*" 
                @change="handleImageUpload" 
                ref="fileInput" 
                class="file-input" 
              />
              <div v-if="form.coverImageUrl" class="image-preview">
                <img :src="form.coverImageUrl" alt="书籍封面" />
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <p>上传封面</p>
              </div>
            </div>
          </el-form-item>
          <p class="image-size-tip">建议尺寸：102*136px </p>
        </div>

        <!-- 类型选择 -->
        <div class="form-group">
          <el-form-item label="选择类型" required>
            <div class="types-container">
              <el-tag
                v-for="type in availableTypes"
                :key="type.id"
                :closable="false"
                :type="form.type === type.id ? 'success' : 'info'"
                @click="selectType(type.id)"
                class="type-btn"
              >
                {{ type.name }}
              </el-tag>
            </div>
          </el-form-item>
          <p class="type-limit-tip">必须选择一个类型</p>
        </div>

        <!-- 标签输入框 -->
        <div class="form-group">
          <el-form-item label="标签" required>
            <el-input
              v-model="form.tagInput"
              placeholder="请输入标签，用空格隔开多个标签"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 简介 -->
        <div class="form-group">
          <el-form-item label="简介" required>
            <el-input
              type="textarea"
              v-model="form.summary"
              placeholder="请输入简介"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-group">
          <el-button type="primary" @click="openDialog">创建书籍</el-button>
        </div>
      </form>
    </div>

    <!-- 审核文本弹窗 -->
    <el-dialog title="请输入审核文本(仅审核可见)" v-model="dialogVisible">
      <el-input
        type="textarea"
        v-model="reviewText"
        maxlength="100"
        placeholder="请输入审核文本，最多100字"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios'; // Import axios for HTTP requests
import router from '@/router';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
// Available types
const availableTypes = ref([
  { id: 1, name: '玄幻' },
  { id: 2, name: '都市' },
  { id: 3, name: '穿越' },
  { id: 4, name:'科幻' },
  { id: 5, name:  '游戏' },
  { id: 6, name: '悬疑' },
  { id: 7, name: '生活' },
]);

// Form default values
const form = ref({
  title: '',
  coverImageUrl: '', // URL for the uploaded image
  type: 0, // Selected single type
  summary: '',
  tagInput: '', // 用户输入的标签字符串
  tags: [] as string[], // 标签数组，用于提交时的处理
});



const reviewText = ref(''); // 审核文本

const dialogVisible = ref(false); // 控制弹窗显示

const fileInput = ref<HTMLInputElement | null>(null);

// Select a single type (only one type can be selected at a time)
const selectType = (typeId: number) => {
  form.value.type = typeId;
};

// Handle cover image upload
const handleImageUpload = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    const formData = new FormData();
    formData.append('file', file);
    console.log('File:', file);
    
    try {
      // Upload the image to the server
      const response = await axios.post(`/file/upload/file`, formData, {
        headers: {
      'Content-Type': 'multipart/form-data',

    },
      });
      
      // Set the cover image URL from the response
      form.value.coverImageUrl = response.data.path; 
      ElMessage({
        message: '图片上传成功',
        type: 'success',
      });
    } catch (error) {
      ElMessage({
        message: '图片上传失败，请重试',
        type: 'error',
      });
      console.error('Error uploading image:', error);
    }
  }
};

// Trigger the file input dialog
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

// 打开审核弹窗
const openDialog = () => {
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  // Convert the tagInput (string) into an array of tags (by splitting with space)
  form.value.tags = form.value.tagInput.trim().split(/\s+/);

  if (!form.value.type) {
    ElMessage({
      message: '必须选择一个类型',
      type: 'error',
    });
    return;
  }

  if (!reviewText.value.trim()) {
    ElMessage({
      message: '请输入审核文本',
      type: 'error',
    });
    return;
  }

  // 提交表单数据，包括审核文本
  const finalFormData = {
    ...form.value,
    authorId: userStore.userInfo.id, // 模拟作者ID
    reviewText: reviewText.value
  };

  console.log('书籍创建表单数据:', finalFormData);
  axios.post('/api/books/create', finalFormData)
    .then(res => {
  
      
      // 提交成功后的逻辑
      dialogVisible.value = false;
      if (res.data.code === 200) {
        ElMessage({
        message: '书籍创建成功',
        type: 'success',
      });
        // 跳转到书籍详情页
       router.push(`/book_show/`+res.data.data.id);
       return;
      }
      ElMessage({
      message: res.data.msg,
      type: 'error',
    });
    
    })
    .catch(() => {
      // 提交失败后的逻辑
      dialogVisible.value = false;
    })

  // Send form data to the server or pass to parent component
  dialogVisible.value = false; // 关闭弹窗
};
</script>

<style scoped>
/* 新增用于居中页面的样式 */
.page-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 3vh;
  min-height: 80vh;
  /* background-color: #f0f0f0; 可选：页面背景色 */
}

.book-create {
  max-width: 600px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fff; /* 将背景色设为白色 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 可选：给表单一个阴影效果 */
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.upload-container {
  width: 102px;
  height: 136px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-placeholder {
  text-align: center;
  color: #aaa;
}

.upload-placeholder el-icon {
  font-size: 24px;
}

.image-preview img {
  max-width: 102px;
  max-height: 136px;
  object-fit: cover;
  border-radius: 4px;
}

.file-input {
  display: none;
}

.image-size-tip {
  font-size: 12px;
  color: #aaa;
  margin-top: 5px;
}

.types-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.type-limit-tip {
  font-size: 12px;
  color: #aaa;
  margin-top: 5px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  display: block;
  width: 100%;
}

/* 弹窗的样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
